<?php

namespace common\models;

use Yii;
use common\helpers\ArrayHelper;
use common\models\user\UserConnect;
use yii\helpers\Json;

/**
 * 第三方登录授权
 * ThirdPartyAuthForm
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ThirdPartyAuthorization extends \common\base\Model {

    /**
     * @var string 外接第三方登录标识
     */
    public $client;

    /**
     * @var string 第三方接口返回的授权code
     */
    public $code;

    /**
     * @var 用户模型
     */
    public $token = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['client', 'code'], 'required'],
            [['client'], 'in', 'range' => UserConnect::getConstants('client'), 'message' => '{attribute}不在允许的授权范围内'],
        ];
    }

    /**
     * bind
     * @return BaseUser|null the saved model or null if saving fails
     */
    public function getAuthData() {
        return null;
    }

    /**
     * bind
     * @return BaseUser|null the saved model or null if saving fails
     */
    public function authent() {
        if (!$this->validate()) {
            $this->dumpError('授权参数校验失败');
        }
        $client = $this->client;
        $code = $this->code;
        $openid = null;
        $unionid = null;
        $data = [];
        if ($client == UserConnect::CLIENT_WECHAT_OPEN) {
            /* @var $wechat \common\components\wechat\WechatOpen */
            $wechat = Yii::$app->openWechat;
            $data = $wechat->getOauth2AccessToken($code);
            $openid = ArrayHelper::getValue($data, 'openid');
            $unionid = ArrayHelper::getValue($data, 'unionid');
        } elseif ($client == UserConnect::CLIENT_WECHAT) {
            if (YII_ENV_PROD) {
                /* @var $wechat \common\components\wechat\MpWechat */
                $wechat = Yii::$app->wechat;
                $data = $wechat->getOauth2AccessToken($code);
            } else {
                $data = [
                    'openid' => Yii::$app->security->generateRandomString(),
                    'unionid' => Yii::$app->security->generateRandomString(),
                    'access_token' => Yii::$app->security->generateRandomString(),
                    'refresh_token' => Yii::$app->security->generateRandomString(),
                    'expires_in' => 7200,
                    'scope' => 'SCOPE',
                ];
            }
            $openid = ArrayHelper::getValue($data, 'openid');
            $unionid = ArrayHelper::getValue($data, 'unionid');
        } elseif ($client == UserConnect::CLIENT_WEIBO) {
            $data = Json::decode($code);
            Yii::error($data, __METHOD__);
            $openid = ArrayHelper::getValue($data, 'uid');
            $unionid = '';
        }
        if (!$openid) {
            Yii::error('缺少授权信息：OPENID');
            return false;
        }
        $condition = compact('client', 'openid', 'unionid');
        $connect = UserConnect::findOrNew($condition);
        if ($unionid) {
            $unionConnect = UserConnect::find()->andWhere([
                'and',
                ['is not', 'user_id', null],
                ['!=', 'unionid', ''],
                ['unionid' => $unionid],
            ])->one();
            if ($unionConnect) {
                $connect->user_id = $unionConnect->user_id;
            }
        }
        Yii::error($connect->attributes);
        if (!$connect->save()) {
            Yii::error('授权成功，保存时发生错误:' . $connect->getErrorMsg());
            return false;
        }

        $connect->setCacheToken($data);
        return $connect;
    }

}
